import datetime
import random
import threading
import time
from io import BytesIO

from django.core.files.storage import Storage
from .settings import *

from .minioClient import go_delete_file, go_upload_file_have_size


file_bucket = BUCKET


def get_time_string():
    """
    :return:
    :PS ：并发较高时尾部随机数增加
    """
    time_string = str(datetime.datetime.fromtimestamp(time.time())).replace("-", "").replace(" ", "").replace(":", "").replace(".", "") + str(random.randint(100, 999))
    return time_string


class ProgressTread(threading.Thread):

    def __init__(self, group=None, target=None, name=None,
                 args=(), kwargs=None, *, daemon=None):
        super().__init__(group=group, target=target, name=name, args=args, kwargs=kwargs, daemon=daemon)
        self.total_length = None
        self.object_name = None
        self.cursor = 0

    def set_meta(self, object_name, total_length):
        print(object_name, total_length)
        self.object_name = object_name
        self.total_length = total_length

    def update(self, cursor):
        print(cursor)
        self.cursor = cursor


class MinioStorage(Storage):
    """
    自定义文件存储系统
    """
    def __init__(self):
        pass

    def _open(self, name, mode='rb'):
        """
        用于打开文件
        :param name: 要打开的文件的名字
        :param mode: 打开文件方式
        :return: None
        """
        pass

    def _save(self, name, content):
        """
        用于保存文件
        :param name: 要保存的文件名字
        :param content: 要保存的文件的内容
        :return: None
        """
        name = name.replace('\\', '/')
        file_path = name.split('.')[0]
        file_name = file_path.split('/')[-1]
        content_name = content.name
        salt = get_time_string()
        if content_name:
            c_name = content_name.split('.')[0]
            name = name.replace(file_name, salt + '_' + c_name)
        else:
            name = name.replace(file_name, salt)
            # name = name.replace(file_name, file_name+'_'+salt)
        byte_data = content.read()
        file_size = content.size
        # 文件太大分块上传 5MiB < part_size < 5GiB, 5242880=5MiB
        part_size = 5242880
        if file_size <= part_size:
            if not byte_data:
                for c in content.chunks(part_size):
                    byte_data = c
            ret = go_upload_file_have_size(BytesIO(byte_data), file_size, bucket=file_bucket, path_name=name)
        else:
            if not byte_data:
                for c in content.chunks(part_size):
                    byte_data += c
            # t = ProgressTread()
            # print(t.ident)
            ret = go_upload_file_have_size(BytesIO(byte_data), file_size, bucket=file_bucket, path_name=name, part_size=part_size)   # , progress=t
        assert ret == 1, '文件上传失败'
        path = name
        return path

    def delete(self, name):
        """
        删除文件
        """
        ret = go_delete_file(bucket=file_bucket, path_name=str(name))
        return ret

    def url(self, name):
        """
        返回name所指文件的绝对URL
        :param name: 要读取文件的引用
        :return:
        """

        host = MINIO_HTTP + MINIO_WEB_HOST + ':' + MINIO_WEB_PORT
        return host + "/" + MINIO_PROXY + '/' + name

    def exists(self, name):
        """
        检查文件存在
        """
        return False
